package util

import (
	"encoding/json"
	"log"
	"net/http"
)

type H struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data,omitempty"`
}

// RespFail 失败响应{code:-1, msg:msg}
func RespFail(w http.ResponseWriter, msg string) {
	Resp(w, -1, nil, msg)
}

// RespOk 成功响应{code:0, msg:msg, data:data}
func RespOk(w http.ResponseWriter, data interface{}, msg string) {
	Resp(w, 0, data, msg)
}

// Resp 任意JSON响应{code:code, msg:msg, data:data}
func Resp(w http.ResponseWriter, code int, data interface{}, msg string) {
	// 设置响应内容为JSON
	w.Header().Set("Content-Type", "application/json")
	// 设置200状态
	w.WriteHeader(http.StatusOK)
	// 输出,一个结构体
	h := H{Code: code, Msg: msg, Data: data}
	// 将结构体转化成JSOn字符串
	ret, err := json.Marshal(h)
	if err != nil {
		log.Println(err.Error())
	}
	_, _ = w.Write(ret) //输出
}
